<?php
namespace app\home\controller;

use app\api\controller\Wechat;
use app\robot\Zfsoft;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\response\Json;

class Robot extends Zfsoft
{

    /**
     * @var int 该机器人所爬的用户的Id
     */
    private $uid;

    /**
     * 调用父类构造方法进行登录操作
     * @param $uid int 在这个系统中的用户id
     * @param $sid string 教务系统账号（学号）
     * @param $password string 教务系统密码
     */
    public function __construct($uid,$sid,$password)
    {
        //存在账号密码再构造
        if ($sid != '' && $password != ''){
            parent::__construct($sid, $password);
        }
        $this->uid=$uid;
    }

    /**
     * 通过教务系统获取成绩信息
     * @param string $b_y 学年
     * @param string $t_m 学期
     * @param false $send 是否发送信息
     * @return Json|string[]
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getScore($b_y='2020',$t_m='1',$send=false)
    {

        //教务系统上面的学期号有点不一样
        $term="3";
        switch ($t_m){
            case '1':
                $term='3';
                break;
            case '2':
                $term='12';
                break;
        }

        //通过父类获取成绩的方法来获取成绩数组
        $GradeData=parent::getScore($b_y,$term);

        //录入数据库

        if (!isset($GradeData['items']))
            return ['result'=>'error','msg'=>'信息获取失败'];

        $Wechat=new Wechat();

        foreach ($GradeData['items'] as $grade)
        {
            //先查询判断是否有重复
            $where=[
                'uid'=>$this->uid,
                'courseCode'=>$grade['kch'],
                'courseName'=>$grade['kcmc'],
                'year'=>$b_y,
                'term'=>$t_m
            ];

            $databaseConnection=db('grade');

            $Grade=$databaseConnection->where($where)->find();

            $databaseConnection->close();

            //没找到当前成绩，说明成绩还没有更新到，就添加进去
            if (empty($Grade))
            {
                $insert['courseName']=$grade['kcmc'];
                $insert['courseCode']=$grade['kch'];
                $insert['score']=$grade['cj'];
                $insert['year']=$b_y;
                $insert['term']=$t_m;
                $insert['uid']=$this->uid;
                $insert['gpa']=$grade['jd'];
                $insert['credit']=$grade['xf'];

                $databaseConnection=db('users');


                //如果更新了成绩就发消息给用户
                $user=$databaseConnection->where('Id',$this->uid)->find();
                $body="你的成绩为：".$grade['cj'];

                send_mail($user['qq'] . "@qq.com", $user["name"], $grade["kcmc"] . "成绩更新了", $body);


                if ($send)
                {
                    $name=$databaseConnection->where('Id',$this->uid)->value('name');

                    $data=[
                        'name1'=>[
                            'value'=>$name
                        ],
                        'number3'=>[
                            'value'=>'10000'
                        ],
                        'thing4'=>[
                            'value'=>$grade['kcmc']
                        ],
                        'number5'=>[
                            'value'=>$grade['cj']
                        ],
                        'thing6'=>[
                            'value'=>$b_y.'年第'.$t_m.'学期'
                        ]
                    ];
                    $Wechat->sendSubscribeMessage($this->uid,$data,'pages/grade/grade','PiqtSH1t_PJYoOQkFN16ttMbEWYnnc0OZqHB49FtJXc');
                }

                $databaseConnection->close();

                $databaseConnection=db('grade');

                $databaseConnection->insert($insert);

                $databaseConnection->close();
            }
        }

        return json($GradeData);
    }

    /**
     * 通过教务系统获取课程表信息
     * @param string $year 学年名
     * @param string $term 学期名
     * @return mixed 课程表信息数组
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     * @throws PDOException
     */
    public function getSchedule($year='2020',$term='1'){

        //教务系统上面的学期号有点不一样
        $t_m="3";
        switch ($term){
            case '1':
                $t_m='3';
                break;
            case '2':
                $t_m='12';
                break;
        }

        $ScheduleData=parent::getSchedule($year,$t_m);

        $ScheduleData=$ScheduleData['kbList'];

        $databaseConnection=\db('table_json');

        //查找是否存在这个用户这学期的课程表
        $existTable=$databaseConnection->where([
            'uid'=>$this->uid,
            'year'=>$year,
            'term'=>$term,
            'type'=>'1'
        ])->find();

        $tableJson=json_encode($ScheduleData,true);
        $tableJson=($tableJson == null  or $tableJson=='null') ? '教务系统登录失败' : $tableJson;


        if (empty($existTable)){

            //如果不存在这个学期的课表数据就插入
            $databaseConnection->insert([
                'uid'=>$this->uid,
                'year'=>$year,
                'term'=>$term,
                'type'=>'1',
                'table_json'=>$tableJson
            ]);

        }else{

            //存在就更新
            $databaseConnection->where([
                'uid'=>$this->uid,
                'year'=>$year,
                'term'=>$term,
                'type'=>'1'
            ])->update(['table_json'=>$tableJson]);
        }

        $databaseConnection->close();

        return $ScheduleData;
    }

    /**
     * 登录超级课程表
     * @return Json
     */
    public function getLogin()
    {
        $url = "http://120.55.151.61/V2/StudentSkip/loginCheckV4.action";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $header = [
            'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
            'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Referer:' . $url
        ];
        //开始模拟登录
        //df35306ebe0f22f0fd31f84e73a0f02b

        $account = "3E28701A184633BEFC43D9DF798E8285";
        $pwd = "C2911C348C57ECCD18A2D54181E59148";
        $data = [
            'platform' => 1,
            'phoneVersion' => 19,
            'deviceCode' => 355757010701395,
            'account' => $account,
            'password' => $pwd,
            'versionNumber' => '9.4.0',
            'updateInfo' => false,
            'channel' => 'ppMarket',
            'phoneBrand' => 'xiaomi',
            'phoneModel' => '',
        ];
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_COOKIEJAR, 'new.cookie');
        curl_setopt($ch, CURLOPT_POST, 1);//post方式提交
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));//要提交的信息
        $json = curl_exec($ch);//执行cURL
        curl_close($ch);//关闭cURL资源，并且释放系统资源
        $json = json_decode($json, true);
        return json($json);
    }

    /**
     * 使用超级课程表获取无课表
     * @param string $superId 超级课程表的课程表id
     * @param string $year 学年号
     * @param string $term 学期号
     * @return bool|string 无课表json数据
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @throws Exception
     * @throws PDOException
     */
    public function getScheduleBySuperId($superId='', $year='', $term='')   //获取课程表
    {

        $this->getLogin();
        $url="http://120.55.151.61/V2/Course/getCourseTableBySuperId.action";
        $ch=curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $header=[
            'User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36',
            'Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
            'Referer:' . $url
        ];

        //开始模拟登录
        if ($superId==''&&$year==''&&$term=='')
        {
            $superId=input('param.superId');
            $year=input('param.year');
            $term=input('param.term');
        }
        $data=[
            'platform'=>1,
            'phoneVersion'=>19,
            'deviceCode'=>355757010701395,
            'versionNumber'=>'9.4.0',
            'updateInfo'=>false,
            'channel'=>'ppMarket',
            'phoneBrand'=>'xiaomi',
            'phoneModel'=>'',
            'term'=>$term,
            'beginYear'=>$year,
            'superId'=>$superId
        ];

        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch,CURLOPT_COOKIEFILE,'new.cookie');
        curl_setopt($ch, CURLOPT_POST, 1);//post方式提交
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));//要提交的信息
        $json=curl_exec($ch);//执行cURL
        $jsonData = json_decode($json, true);

        //获取课程列表

        if(isset($jsonData['data'])){
            $courseList=$jsonData['data']['courseList'];

            $databaseConnection=\db('table_json');

            //查找是否存在这个用户这学期的超级课程表
            $existTable=$databaseConnection->where([
                'uid'=>$this->uid,
                'year'=>$year,
                'term'=>$term,
                'type'=>'0'
            ])->find();

            $tableJson=json_encode($courseList,true);

            if (empty($existTable)){

                //如果不存在这个学期的课表数据就插入
                $databaseConnection->insert([
                    'uid'=>$this->uid,
                    'year'=>$year,
                    'term'=>$term,
                    'type'=>'0',
                    'table_json'=>$tableJson
                ]);

            }else{


                //存在就更新
                $databaseConnection->where([
                    'uid'=>$this->uid,
                    'year'=>$year,
                    'term'=>$term,
                    'type'=>'0'
                ])->update(['table_json'=>$tableJson]);
            }

            $databaseConnection->close();
            return $json;
        }else{
            return "{}";
        }




    }
}
